package com.iyao_app.mvp.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.iyao_app.R;
import com.iyao_app.base.BaseActivity;
import com.iyao_app.entry.Manor;
import com.iyao_app.util.Contants;
import com.iyao_app.util.ResourcesUtils;
import com.iyaowoqu.base_library.util.KeyboardUtils;
import com.iyaowoqu.base_library.util.LogUtil;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/27.
 */

public class SearchActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.et_search)
    EditText mEtSearch;
    @BindView(R.id.iv_delete)
    ImageView mIvDelete;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.frame_content)
    FrameLayout mFrameContent;

    private String city;
    private SearchFragment searchFragment;
    private SearchResultFragment searchResultFragment;
    private int type;
    private Manor manor;
    public static int RESULT_CODE = 18;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acrivity_search);
        ButterKnife.bind(this);

        city = getIntent().getStringExtra(Contants.OTHER_FIELD);
        manor = (Manor) getIntent().getSerializableExtra(Contants.THIRD_FIELD);
        type = getIntent().getIntExtra(Contants.CLASS_TYPE, 0);
        init();
    }

    private void init() {
        mIvDelete.setOnClickListener(this);
        mIvBack.setOnClickListener(this);
        SpannableString s = new SpannableString(ResourcesUtils.getString(R.string.search_hint));
        AbsoluteSizeSpan textSize = new AbsoluteSizeSpan(13, true);
        s.setSpan(textSize, 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mEtSearch.setHint(s);
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    mIvDelete.setVisibility(View.VISIBLE);
                } else {
                    mIvDelete.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH)) {
                    KeyboardUtils.hideSoftInput(SearchActivity.this);
                    if (TextUtils.isEmpty(mEtSearch.getText().toString().trim())) {
//                            Toast.makeText(SearchActivity.this, "请输入地点关键字", Toast.LENGTH_SHORT).show();
                        show(0);
                    } else {
                        show(1);
                        searchResultFragment.search(mEtSearch.getText().toString().trim(), city);
                    }


                    return true;
                }

                return false;
            }
        });
        show(0);
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    private void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        KeyboardUtils.showSoftInput(this);
    }

    private void show(int position) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        searchFragment = (SearchFragment) fragmentManager.findFragmentByTag(SearchFragment.class.getSimpleName());
        searchResultFragment = (SearchResultFragment) fragmentManager.findFragmentByTag(SearchResultFragment.class.getSimpleName());
        switch (position) {
            case 0:
                if (searchFragment == null) {
                    searchFragment = new SearchFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString(Contants.OTHER_FIELD, city);
                    bundle.putSerializable(Contants.THIRD_FIELD, manor);
                    bundle.putInt(Contants.CLASS_TYPE, type);
                    searchFragment.setArguments(bundle);
                    transaction.add(R.id.frame_content, searchFragment, SearchFragment.class.getSimpleName());
                }
                transaction.show(searchFragment);
                if (searchResultFragment != null) {
                    transaction.hide(searchResultFragment);
                }
                break;
            case 1:
                if (searchResultFragment == null) {
                    searchResultFragment = new SearchResultFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString(Contants.OTHER_FIELD, city);
                    bundle.putSerializable(Contants.THIRD_FIELD, manor);
                    bundle.putInt(Contants.CLASS_TYPE, type);
                    searchResultFragment.setArguments(bundle);
                    transaction.add(R.id.frame_content, searchResultFragment, SearchResultFragment.class.getSimpleName());
                }
                transaction.show(searchResultFragment);
                if (searchFragment != null) {
                    transaction.hide(searchFragment);
                }
                break;
        }
        transaction.commit();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.lin_location:

                break;
            case R.id.iv_delete:
                mEtSearch.setText("");
                LogUtil.e("======iv_delete=======");
                showSoftInputFromWindow(mEtSearch);
//                show(0);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private final int REQUEST_CODE = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("=-==onActivityResult !==" + resultCode);
        if (resultCode == SearchActivity.RESULT_CODE) {
            LogUtil.e("=-==REQUEST_CODE !==");
            if (data != null) {
                Manor manor = (Manor) data.getSerializableExtra(Contants.TYPE);
                if (manor != null) {
                    Intent intent = new Intent();
                    intent.putExtra(Contants.TYPE, manor);
                    setResult(SearchActivity.RESULT_CODE, intent);
                    finish();
                }
            }
        }
    }
}
